package com.tannm.doan.taskmanager.activities;

import java.util.*;

import com.tannm.doan.taskmanager.CommonActivity;
import com.tannm.doan.taskmanager.RepeatData;
import com.tannm.doan.taskmanager.database.DataRowAppointment;
import com.tannm.doan.taskmanager.database.DataTable;
import com.tannm.doan.widgets.*;

import com.tannm.doan.taskmanager.R;
import android.content.Intent;
import android.os.Bundle;
import android.widget.*;
import android.view.*;

//New appointment activity
public class ActivityAppointment extends CommonActivity {
	// fields
	private Calendar dateStart = null;
	private DataRowAppointment dataRow = null;
	private DataTable dataTable = null;

	// views
	private TouchEdit edSubject = null;
	private Button btnStartDate = null;
	private Button btnStartTime = null;
	private CheckBox chkAllDay = null;
	private CheckBox chkAlarm = null;
	private Button btnRepeatSelect = null;

	private ImageButton btnDelete = null;
	private ImageButton btnSave = null;

	// repeat data
	private int iRepeatType = -1;
	private int iRepeatEvery = 0;
	private Calendar dateEndOn = null;

	// methods
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.appointment);

		// initialize objects
		dataRow = new DataRowAppointment(userdb);
		dataTable = new DataTable(dataRow);

		// check startup mode and open data
		if (getStartMode() == StartMode.EDIT)
			if (!openDataForEdit(dataTable))
				finish();

		// initialize views
		initViews();
		initState();
	}

	@Override
	public void onStart() {
		super.onStart();

	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public void onPause() {
		super.onPause();

	}

	private void initViews() {
		edSubject = (TouchEdit) findViewById(R.id.edAppointmentSubject);
		edSubject.setOnOpenKeyboard(new TouchEdit.OnOpenKeyboard() {
			public void OnOpenKeyboardEvent() {
				KeyboardWidget.open(ActivityAppointment.this, edSubject
						.getText().toString());
			}
		});

		btnStartDate = (Button) findViewById(R.id.btnAppointmentStartDate);
		btnStartTime = (Button) findViewById(R.id.btnAppointmentStartTime);
		chkAllDay = (CheckBox) findViewById(R.id.chkAppointmentAllDay);
		chkAlarm = (CheckBox) findViewById(R.id.chkAppointmentAlarm);

		btnRepeatSelect = (Button) findViewById(R.id.btnRepeatSelect);
		btnRepeatSelect.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				openRepeatDialog();
			}
		});

		btnSave = (ImageButton) findViewById(R.id.btnAppointmentSave);
		btnSave.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				saveData();
			}
		});

		btnDelete = (ImageButton) findViewById(R.id.btnAppointmentDelete);
		btnDelete.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				deleteData();
			}
		});

		btnStartDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				DateWidget.open(ActivityAppointment.this, false, dateStart,
						prefs.iFirstDayOfWeek);

			}
		});

		btnStartTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				TimeWidget.open(ActivityAppointment.this, false,
						prefs.b24HourMode, dateStart.get(Calendar.HOUR_OF_DAY),
						dateStart.get(Calendar.MINUTE));

			}
		});

		chkAllDay.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				updateStartDateTimeView();
			}
		});

	}

	private void setStartDateByAgendaView(Calendar calDate) {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				if (extras.containsKey(CommonActivity.bundleAgendaView)) {
					int iView = extras.getInt(CommonActivity.bundleAgendaView);
					if (iView == 1) // day
					{
						long lStartDate = extras
								.getLong(CommonActivity.bundleAgendaViewStartDate);
						calDate.setTimeInMillis(lStartDate);
					}
				}
			}
		}
	}

	private void setStartTimeForDayAgendaView(Calendar calDate) {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				if (extras.containsKey(CommonActivity.bundleHourOfDay)) {
					int iView = extras.getInt(CommonActivity.bundleAgendaView);
					if (iView == 1) // day
					{
						int iHourOfDay = extras
								.getInt(CommonActivity.bundleHourOfDay);
						int iMinutes = extras
								.getInt(CommonActivity.bundleMinutes);
						calDate.set(Calendar.HOUR_OF_DAY, iHourOfDay);
						calDate.set(Calendar.MINUTE, iMinutes);
					}
				}
			}
		}
	}

	private void updateStartDateTimeForNewAppointment(Calendar calDate) {
		int iHour = calDate.get(Calendar.HOUR_OF_DAY);
		int iMinute = calDate.get(Calendar.MINUTE);

		if (iHour < 23)
			iHour += 1;
		iMinute = 0;

		calDate.set(Calendar.HOUR_OF_DAY, iHour);
		calDate.set(Calendar.MINUTE, iMinute);
		calDate.set(Calendar.SECOND, 0);
		calDate.set(Calendar.MILLISECOND, 0);
	}

	private void initState() {
		// title
		String sSubTitle = utils.getResStr(R.string.titleDefaultAppointment);

		// date values
		dateStart = Calendar.getInstance();
		dateEndOn = Calendar.getInstance();

		dataRow.setDuration(prefs.iMinutesDuration);

		// INSERT MODE
		if (getStartMode() == StartMode.NEW) {
			sSubTitle = utils.getResStr(R.string.titleNewAppointment);
			btnDelete.setVisibility(View.INVISIBLE);

			// initialize data
			setStartDateByAgendaView(dateStart);
			updateStartDateTimeForNewAppointment(dateStart);
			setStartTimeForDayAgendaView(dateStart);

			chkAllDay.setChecked(false);
			chkAlarm.setChecked(true);

			// repeat data
			iRepeatType = 0; // none
			iRepeatEvery = 1;
			dateEndOn.setTimeInMillis(0); // no end date
		}

		// EDIT MODE
		if (getStartMode() == StartMode.EDIT) {
			sSubTitle = utils.getResStr(R.string.titleEditAppointment);

			dateStart.setTimeInMillis(dataRow.getStartDate().getTimeInMillis());

			btnDelete.setVisibility(View.VISIBLE);
			edSubject.setText(dataRow.getSubject());
			chkAllDay.setChecked(dataRow.getAllDay());
			chkAlarm.setChecked(dataRow.getAlarm());

			// repeat data
			iRepeatType = dataRow.getRepeat().getRepeatTypeAsInt();
			iRepeatEvery = dataRow.getRepeat().getEvery();
			dateEndOn.setTimeInMillis(dataRow.getRepeat().getEndOnDate()
					.getTimeInMillis());
		}

		restoreStateFromFreezeIfRequired();

		setActivityTitle(sSubTitle);
		updateStartDateTimeView();

		updateRepeatInfo();

		// set focus to subject
		edSubject.requestFocus();
		if (getStartMode() == StartMode.EDIT)
			edSubject.setSelection(edSubject.length());
	}

	private void updateRepeatInfo() {
		btnRepeatSelect.setText(getRepeatInfo());
	}

	private String getRepeatInfo() {
		String s = utils.getResStr(R.string.strRepeatTypeNone);
		String sUntil = utils.getResStr(R.string.strRepeatInfoUntil);
		String sEndDate = (dateEndOn.getTimeInMillis() == 0) ? "" : " "
				+ sUntil + " " + utils.getLongDate(dateEndOn);
		// daily
		if (iRepeatType == 1)
			s = String.format(utils.getResStr(R.string.strRepeatInfoDaily),
					iRepeatEvery, sEndDate);
		// weekly
		if (iRepeatType == 2)
			s = String.format(utils.getResStr(R.string.strRepeatInfoWeekly),
					iRepeatEvery, sEndDate);
		// monthly
		if (iRepeatType == 3)
			s = String.format(utils.getResStr(R.string.strRepeatInfoMonthly),
					iRepeatEvery, sEndDate);
		// monthly
		if (iRepeatType == 4)
			s = String.format(utils.getResStr(R.string.strRepeatInfoYearly),
					sEndDate);
		return s;
	}

	private void updateStartDateTimeView() {
		btnStartDate.setText(utils.getLongDate(dateStart));
		if (chkAllDay.isChecked()) {
			btnStartTime.setText(utils.getResStr(R.string.labNoTime));
		} else {
			btnStartTime.setText(utils
					.getLongTime(dateStart, prefs.b24HourMode));
		}
	}

	protected void onSizeChanged(int w, int h, int oldw, int oldh) {

	}

	public void saveData() {
		// check date if no repeat
		if ((iRepeatType == 0) && (dateBeforeNow(dateStart)))
			return;

		dataRow.setSubject(edSubject.getText().toString());
		dataRow.setStartDate(dateStart);
		dataRow.setAllDay(chkAllDay.isChecked());
		dataRow.setAlarm(chkAlarm.isChecked());

		// set repeat type
		RepeatData rd = dataRow.getRepeat();
		rd.setRepeatTypeAsInt(iRepeatType);
		rd.setEvery(iRepeatEvery);
		rd.setEndOnDate(dateEndOn.getTimeInMillis());

		if (saveDataToTable(dataTable))
			closeActivity(dataTable);
	}

	public void deleteData() {
		if (deleteDataFromTable(dataTable))
			closeActivity(dataTable);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Bundle extras = CommonActivity.getIntentExtras(data);
		if (extras != null) {

			// check for repeat update
			if (ActivityAppointmentRepeat.getActivityResult(requestCode,
					resultCode, extras)) {
				iRepeatType = ActivityAppointmentRepeat
						.getExtraRepeatType(extras);
				iRepeatEvery = ActivityAppointmentRepeat
						.getExtraRepeatEvery(extras);
				dateEndOn.setTimeInMillis(ActivityAppointmentRepeat
						.getExtraRepeatEndOnDate(extras));
				updateRepeatInfo();
				return;
			}

			// check for date widget edit request code
			if (requestCode == DateWidget.SELECT_DATE_REQUEST) {
				final long lDate = DateWidget.getSelectedDateOnActivityResult(
						requestCode, resultCode, extras, dateStart);
				if (lDate != -1) {
					updateStartDateTimeView();
					return;
				}
			}

			// check for time widget edit request code
			if ((requestCode == TimeWidget.SELECT_TIME_REQUEST)
					&& (resultCode == RESULT_OK)) {
				final int iHour = TimeWidget
						.getSelectedTimeHourOnActivityResult(requestCode,
								resultCode, extras);
				final int iMinute = TimeWidget
						.getSelectedTimeMinuteOnActivityResult(requestCode,
								resultCode, extras);
				dateStart.set(Calendar.HOUR_OF_DAY, iHour);
				dateStart.set(Calendar.MINUTE, iMinute);
				chkAllDay.setChecked(false);
				updateStartDateTimeView();
				return;
			}

			// get KeyboardWidget result
			if ((requestCode == KeyboardWidget.EDIT_TEXT_REQUEST)
					&& (resultCode == RESULT_OK)) {
				String sText = KeyboardWidget.getTextOnActivityResult(
						requestCode, resultCode, extras);
				edSubject.setText(sText);
				return;
			}

		}
	}

	public void openRepeatDialog() {
		ActivityAppointmentRepeat.openRepeatForEdit(this,
				bundleOtherDataStartup, iRepeatType, iRepeatEvery, dateEndOn
						.getTimeInMillis());
	}

	@Override
	public void saveDateValuesBeforeChange(Bundle data) {
		super.saveDateValuesBeforeChange(data);
		if (getStartMode() == StartMode.EDIT) {
			data.putLong("dateStart", dataRow.getStartDate().getTimeInMillis());
			data.putLong("dateEndOn", dataRow.getRepeat().getEndOnDate()
					.getTimeInMillis());
		}
	}

	@Override
	public boolean dateValuesChanged(Bundle data) {
		super.dateValuesChanged(data);
		if (getStartMode() == StartMode.EDIT) {
			if (dateStart.getTimeInMillis() != data.getLong("dateStart"))
				return true;
		}
		return false;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// save controls state
		outState.putString("subject", edSubject.getText().toString());
		outState.putBoolean("alarm", chkAlarm.isChecked());
		outState.putLong("dateStart", dateStart.getTimeInMillis());
		outState.putBoolean("allday", chkAllDay.isChecked());
		outState.putInt("repeatType", iRepeatType);
		outState.putInt("repeatEvery", iRepeatEvery);
		outState.putLong("dateEndOn", dateEndOn.getTimeInMillis());
	}

	@Override
	protected void restoreStateFromFreeze() {
		edSubject.setText(freeze.getString("subject"));
		chkAlarm.setChecked(freeze.getBoolean("alarm"));
		dateStart.setTimeInMillis(freeze.getLong("dateStart"));
		chkAllDay.setChecked(freeze.getBoolean("allday"));
		iRepeatType = freeze.getInt("repeatType");
		iRepeatEvery = freeze.getInt("repeatEvery");
		dateEndOn.setTimeInMillis(freeze.getLong("dateEndOn"));
	}

}
